var express = require("express");
var router = express.Router();
var iconv = require("iconv-lite"); // 处理中文乱码
var multer = require("multer");
var path = require("path");
const XLSX = require("xlsx");
const axios = require("axios");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log("req", req);
    console.log("file", file);
    cb(null, path.join(__dirname, "../public/images")); // 存储位置
  },
  filename: function (req, file, cb) {
    const _time = Date.now().toString().slice(-4);
    cb(
      null,
      `-${_time}-${iconv.decode(file.originalname, "utf-8")}` // 存储文件名称处理
    );
  },
});

var upload = multer({ storage: storage }).single("file");
router.post("/uploadFile", upload, async function (req, res, next) {
  const { file } = req;
  res.json({
    code: "S0001",
    fileStr: "/images/" + file.filename,
  });
});
async function getResponseByXlsxPath(path) {
  return await axios({
    url: path,
    method: "GET",
    responseType: "arraybuffer", // 设置响应类型为ArrayBuffer
  });
}
async function getXlsx(filePath) {
  const response = await getResponseByXlsxPath(filePath);
  const workbook = XLSX.read(response.data, { type: "buffer" });
  // 获取工作表的名称列表
  const sheetNames = workbook.SheetNames;
  // 使用第一个工作表
  const sheet = workbook.Sheets[sheetNames[0]];
  // 将工作表对象转换为JSON
  const data = XLSX.utils.sheet_to_json(sheet);
  console.log(data, sheetNames);
}

module.exports = router;
